var closeTabsToTheRight = {};

gBrowser.warncloseRightTab = function (rTabs) {
	var prefsService = Services.prefs;
	var warnOnClose = prefsService.getBoolPref("browser.tabs.warnOnClose");
	var warnOnCloseOtherTabs = prefsService.getBoolPref("browser.tabs.warnOnCloseOtherTabs");
	var bundle = this.mStringBundle;
	var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
	var check = {value: true};
	if (rTabs.length >= 2) {
		var button;
		if (warnOnClose) {
			button = prompts.confirmEx(window, 
				bundle.getString("tabs.closeWarningTitle"), 
				bundle.getFormattedString("tabs.closeWarningMultipleTabs", [rTabs.length]), 
				(prompts.BUTTON_TITLE_IS_STRING * prompts.BUTTON_POS_0) + (prompts.BUTTON_TITLE_CANCEL * prompts.BUTTON_POS_1),
				bundle.getString("tabs.closeButtonMultiple"), 
				null, null, 
				bundle.getString("tabs.closeWarningPromptMe"),
				check);

			if (button === 0) {
				prefsService.setBoolPref("browser.tabs.warnOnClose", check.value);
				return true;
			} else {
				return false;
			}
		} else if (warnOnCloseOtherTabs) {
			button = prompts.confirmEx(window, 
				bundle.getString("tabs.closeWarningTitle"), 
				bundle.getFormattedString("tabs.closeWarningMultipleTabs", [rTabs.length]), 
				(prompts.BUTTON_TITLE_IS_STRING * prompts.BUTTON_POS_0) + (prompts.BUTTON_TITLE_CANCEL * prompts.BUTTON_POS_1),
				bundle.getString("tabs.closeButtonMultiple"), 
				null, null, 
				null,
				check);
			return (button === 0);
		}
	}
	return true;
};

closeTabsToTheRight.getRightUnpinnedTabsOf = function _getRightUnpinnedTabsOf(aTab) {
	var tabs = gBrowser.tabs,
	ret = [];

	for (var i = tabs.length - 1; i >= 0; --i) {
		var t = tabs[i];
		if (t === aTab) {
			break;
		}
		if (t.pinned) {
			continue;
		}
		ret.unshift(t);
	}

	return ret;
};

closeTabsToTheRight.removeRightTabsOf = function _removeRightTabsOf(aTab) {
	var rTabs = closeTabsToTheRight.getRightUnpinnedTabsOf(aTab);

	if (gBrowser.warncloseRightTab(rTabs)) {
		for (var i = rTabs.length - 1; i >= 0; --i) {
			gBrowser.removeTab(rTabs[i], {animate:true});
		}
	}
};

//Set menuitem's state
window.addEventListener("load", function() {
	document.getElementById("tabContextMenu").addEventListener("popupshowing", function(ev){
		//Must be called after TabContextMenu.updateContextMenu(menupopup)
		if (ev.target !== this) { return; }

		var rTabs = closeTabsToTheRight.getRightUnpinnedTabsOf(TabContextMenu.contextTab);
		document.getElementById("context_closeTabsToTheRight").disabled = !rTabs.length;
	}, false);
}, false);

